package cn.skyquant.quant4j.service.boot.model.ea;

import cn.skyquant.quant4j.api.dto.ResultDTO;
import cn.skyquant.quant4j.api.ea.EAManagerDTO;
import cn.skyquant.quant4j.api.ea.EAService;
import cn.skyquant.quant4j.api.enums.BorkerType;
import cn.skyquant.quant4j.api.enums.RunStatus;
import cn.skyquant.quant4j.api.sms.SmsService;
import cn.skyquant.quant4j.sdk.enums.Status;
import cn.skyquant.quant4j.sdk.util.bean.BeanTools;
import cn.skyquant.quant4j.sdk.util.time.CalendarUtils;
import cn.skyquant.quant4j.service.boot.model.account.Account;
import cn.skyquant.quant4j.service.boot.model.account.AccountRepository;
import cn.skyquant.quant4j.service.boot.model.authority.Role;
import cn.skyquant.quant4j.service.boot.model.authority.User;
import cn.skyquant.quant4j.service.boot.model.authority.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service("EAServiceImpl")
public class EAServiceImpl implements EAService {

    @Autowired
    EaManagerRepository eaManagerRepository;

    @Autowired
    SmsService smsService;

    @Autowired
    UserRepository userRepository;

    @Autowired
    AccountRepository accountRepository;

    private static ResultDTO error = ResultDTO.error("未找到EA配置,请联系管理员");

    @Override
    public ResultDTO<EAManagerDTO> getByKey(String ea, Integer eaId, String accountCode, BorkerType borkerType) {
        Optional<Account> optionalAccount = accountRepository.findByCodeAndBorkerType(accountCode,borkerType);
        if(optionalAccount.isPresent()){
            Account account = optionalAccount.get();
            Optional<EaManager> eaManagerOptional = eaManagerRepository.getByKey(ea,eaId,account);
            if(eaManagerOptional.isPresent()){
                EaManager eaManager = eaManagerOptional.get();
                EAManagerDTO eaManagerDTO = convertDoToDto(eaManager);
                return ResultDTO.success(eaManagerDTO);
            }
        }
        return error;
    }

    @Transactional
    @Override
    public ResultDTO<EAManagerDTO> getOrCreate(String ea, Integer eaId, Integer accountId) {
        Optional<Account> optionalAccount = accountRepository.findById(accountId);
        if(optionalAccount.isPresent()){
            Account account = optionalAccount.get();
            Optional<EaManager> eaManagerOptional = eaManagerRepository.getByKey(ea,eaId,account);
            if(eaManagerOptional.isPresent()){
                EaManager eaManager = eaManagerOptional.get();
                EAManagerDTO eaManagerDTO = convertDoToDto(eaManager);
                return ResultDTO.success(eaManagerDTO);
            }else {
                EaManager eaManager = new EaManager();
                eaManager.account = account;
                eaManager.eaId = eaId;
                eaManager.ea = ea;
                eaManager.eaStatus = Status.A;//默认是可以运行的状态
                eaManager = eaManagerRepository.save(eaManager);
                EAManagerDTO eaManagerDTO = convertDoToDto(eaManager);
                return ResultDTO.success(eaManagerDTO);
            }
        }
        return error;
    }

    @Transactional
    @Override
    public ResultDTO<Void> ready(Integer id, String hostname, String localIp,String remoteIp) {
        Optional<EaManager> eaManagerOptional = eaManagerRepository.findById(id);
        if(eaManagerOptional.isPresent()){
            EaManager eaManager = eaManagerOptional.get();
            eaManager.hostname = hostname;
            eaManager.localIp = localIp;
            eaManager.remoteIp = remoteIp;
            eaManager.runStatus = RunStatus.READY;
            eaManager.stopTime = null;
            return ResultDTO.success;
        }
        return ResultDTO.error2;
    }

    @Transactional
    @Override
    public ResultDTO<Void> start(Integer id) {
        Date date= new Date();
        Optional<EaManager> eaManagerOptional = eaManagerRepository.findById(id);
        if(eaManagerOptional.isPresent()){
            EaManager eaManager = eaManagerOptional.get();
            eaManager.runStatus = RunStatus.RUNNING;
            eaManager.startTime = date;
            eaManager.heartbeat0 = date;
            eaManager.heartbeat1 = date;
            eaManager.heartbeat2 = date;
            eaManager.stopTime = null;
            smsnoticy(eaManager.account.id,eaManager.ea,eaManager.runStatus);
            return ResultDTO.success;
        }
        return ResultDTO.error2;
    }

    @Transactional
    @Override
    public ResultDTO<Void> stop(Integer id) {
        Date date= new Date();
        Optional<EaManager> eaManagerOptional = eaManagerRepository.findById(id);
        if(eaManagerOptional.isPresent()){
            EaManager eaManager = eaManagerOptional.get();
            eaManager.runStatus = RunStatus.STOP;
            eaManager.stopTime = date;
            smsnoticy(eaManager.account.id,eaManager.ea,eaManager.runStatus);
            return ResultDTO.success;
        }
        return ResultDTO.error2;
    }

    @Transactional
    @Override
    public ResultDTO<Void> heartbeat(Integer id, String borkerTime,String remoteIp) {
        Date date= new Date();
        Optional<EaManager> eaManagerOptional = eaManagerRepository.findById(id);
        if(eaManagerOptional.isPresent()){
            EaManager eaManager = eaManagerOptional.get();
            eaManager.heartbeat2 = new Date(eaManager.heartbeat1.getTime());
            eaManager.heartbeat1 = new Date(eaManager.heartbeat0.getTime());
            eaManager.heartbeat0 = date;
            eaManager.remoteIp = remoteIp;
            try {
                eaManager.borkerTime = CalendarUtils.parseTightStandard(borkerTime);
            } catch (ParseException e) {

            }
            eaManager.runStatus = RunStatus.RUNNING;
            return ResultDTO.success;
        }
        return ResultDTO.error2;
    }

    private void smsnoticy(Integer accountId,String ea, RunStatus status){
        Optional<Account> optionalAccount = accountRepository.findById(accountId);
        List<User> users = userRepository.findByRoles(Role.administrator);
        if(optionalAccount.isPresent()){
            Account account = optionalAccount.get();
            String accountname = account.name;
            if(account.user!=null && account.user.name!=null){
                accountname = account.user.name;
            }
            for(User user:users){
                smsService.eaStatus(user.tel,accountname,account.code,ea,status);
            }
        }
    }

    private static EAManagerDTO convertDoToDto(EaManager entity) {
        EAManagerDTO dto = new EAManagerDTO();
        BeanTools.copyPublicFields(entity,dto);
        return dto;
    }

    private static List<EAManagerDTO> convertDoToDtos(List<EaManager> list) {
        return list.stream().map(x->convertDoToDto(x)).collect(Collectors.toList());
    }
}
